package com.xy.bioapi.controller;

import com.xy.bioapi.entity.Result;
import com.xy.bioapi.entity.Test;
import com.xy.bioapi.entity.TestResult;
import com.xy.bioapi.enums.ResultEnum;
import com.xy.bioapi.service.TestResultService;
import com.xy.bioapi.service.TestService;
import com.xy.bioapi.utils.ResultUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

/**
 * 设备数据接口
 * Created by DELL on 2017/7/10.
 */
@RestController
@RequestMapping(value = "/chipInterface/rest/{version}")
public class ChipInterfaceController {

    @Autowired
    private TestService testService;

    @Autowired
    private TestResultService testResultService;


    /**
     * 上传实验数据
     * @param test
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/updateTest",method = RequestMethod.POST)
    public Result<Test> updateTest(@Valid Test test, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return ResultUtil.error(ResultEnum.ILLEGAL_EQUIPMENT_ID);
        }
        testService.saveTest(test);
        return ResultUtil.success(ResultEnum.INVOKE_SUCCESS);
    }

    /**
     * 通过设备ID获取该设备实验数据集合
     * @param equipmentId
     * @return
     */
    @RequestMapping(value = "/getTest",method = RequestMethod.POST)
    public Result<Test> getTest(@RequestParam(value = "equipmentId") Long equipmentId){
        Set<Test> tests = testService.getTestByEquipmentId(equipmentId);
        return ResultUtil.success(ResultEnum.INVOKE_SUCCESS,tests);
    }

    /**
     * 上传实验结果数据
     * @param testResult
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/updateTestResult",method = RequestMethod.POST)
    public Result<TestResult> updateTestResult(@Valid TestResult testResult, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return ResultUtil.error(ResultEnum.ILLEGAL_EQUIPMENT_ID);
        }
        testResultService.saveTestResult(testResult);
        return ResultUtil.success(ResultEnum.INVOKE_SUCCESS);
    }

    /**
     * 通过设备ID获取该设备实验结果数据集合
     * @param equipmentId
     * @return
     */
    @RequestMapping(value = "/getTestResult",method = RequestMethod.POST)
    public Result<TestResult> getTestResult(@RequestParam(value = "equipmentId") Long equipmentId){
        Set<TestResult> testResults = testResultService.getTestResultByEquipmentId(equipmentId);
        return ResultUtil.success(ResultEnum.INVOKE_SUCCESS,testResults);
    }

    /**
     * 统一调用入口
     * @param method
     */
//    @RequestMapping(value = "/getService",method = RequestMethod.POST)
    @PostMapping(value="/getService")
    public Object getService(@RequestParam(value = "mehtod") String method,@RequestParam(value = "field",defaultValue = "{}") String field){
        if(method == null) {
            return ResultUtil.error(ResultEnum.INVAILD_METHOD);
            //上传实验结果数据
        }else if(method.equals("set.experimentResult.data")){
            JSONObject jsonObject = JSONObject.fromObject(field);
            //实例化数据
            TestResult testResult = new TestResult();
            testResult.setEquipmentId(Long.parseLong(jsonObject.get("equipmentId").toString()));
            testResult.setQuota_data(jsonObject.get("quota_data"));
            testResult.setCreateDate(new Date());//创建时间
            testResult.setAd(jsonObject.get("ad").toString());
            testResult.setAge(jsonObject.get("age").toString());
            testResult.setBed(jsonObject.get("bed").toString());
            testResult.setCd(jsonObject.get("cd").toString());
            testResult.setChipno(jsonObject.get("chipno").toString());
            testResult.setDepartment(jsonObject.get("department").toString());
            testResult.setDoctor(jsonObject.get("doctor").toString());
            testResult.setGender(jsonObject.get("gender").toString());
            testResult.setName(jsonObject.get("name").toString());
            testResult.setRoom(jsonObject.get("room").toString());
            testResult.setSampleno(jsonObject.get("sampleno").toString());
            testResult.setSampletype(jsonObject.get("sampletype").toString());

            String applicationTimeString = jsonObject.get("applicationtime").toString().replace("/","-");
            String receivetTmeString = jsonObject.get("receivetime").toString().replace("/","-");
            String checkTime = jsonObject.get("checktime").toString();

            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try{
                if(applicationTimeString != null && !"".equals(applicationTimeString)){
                    testResult.setApplicationtime(df.parse(applicationTimeString));
                }else {
                    testResult.setApplicationtime(null);
                }
                if(receivetTmeString != null && !"".equals(receivetTmeString)){
                    testResult.setReceivetime(df.parse(receivetTmeString));
                }else {
                    testResult.setReceivetime(null);
                }
                if(checkTime != null && !"".equals(checkTime)){
                    testResult.setChecktime(df.parse(checkTime));
                }else{
                    testResult.setChecktime(new Date());
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            //保存
            testResultService.saveTestResult(testResult);
            return  ResultUtil.success(ResultEnum.INVOKE_SUCCESS);

            //上传实验数据
        }else if(method.equals("set.experiment.data")){
            JSONObject jsonObject = JSONObject.fromObject(field);
            Test test = new Test();
            test.setEquipmentId(Long.parseLong(jsonObject.get("equipmentId").toString()));
            test.setTesting_date(jsonObject.get("testing_date").toString());
            test.setCurve_data(jsonObject.get("curve_data"));
            test.setQuota_data(jsonObject.get("quota_data"));
            test.setTemperature_data(jsonObject.get("temperature_data"));
            test.setCreateDate(new Date());
            test.setAd(jsonObject.get("ad").toString());
            test.setAge(jsonObject.get("age").toString());
            test.setBed(jsonObject.get("bed").toString());
            test.setCd(jsonObject.get("cd").toString());
            test.setChipno(jsonObject.get("chipno").toString());
            test.setDepartment(jsonObject.get("department").toString());
            test.setDoctor(jsonObject.get("doctor").toString());
            test.setGender(jsonObject.get("gender").toString());
            test.setName(jsonObject.get("name").toString());
            test.setRoom(jsonObject.get("room").toString());
            test.setSampleno(jsonObject.get("sampleno").toString());
            test.setSampletype(jsonObject.get("sampletype").toString());

            String applicationTimeString = jsonObject.get("applicationtime").toString().replace("/","-");
            String receivetTmeString = jsonObject.get("receivetime").toString().replace("/","-");
            String checkTime = jsonObject.get("checktime").toString();

            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try{
                if(applicationTimeString != null && !"".equals(applicationTimeString)){
                    test.setApplicationtime(df.parse(applicationTimeString));
                }else{
                    test.setApplicationtime(null);
                }
                if(receivetTmeString != null && !"".equals(receivetTmeString)){
                    test.setReceivetime(df.parse(receivetTmeString));
                }else{
                    test.setReceivetime(null);
                }
                if(checkTime != null && !"".equals(checkTime)){
                    test.setChecktime(df.parse(checkTime));
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            testService.saveTest(test);
            return ResultUtil.success(ResultEnum.INVOKE_SUCCESS);
            //获取实验结果数据
        }else if(method.equals("get.experimentResult.data")){
            JSONObject jsonObject = JSONObject.fromObject(field);
            Set<TestResult> testResults = testResultService.getTestResultByEquipmentId(Long.parseLong(jsonObject.get("equipmentId").toString()));
            if(testResults == null){
                return ResultUtil.error(ResultEnum.ILLEGAL_EQUIPMENT_ID);
            }else {
                return ResultUtil.success(ResultEnum.INVOKE_SUCCESS,testResults);
            }

            //获取实验数据
        }else if(method.equals("get.experiment.data")){
            JSONObject jsonObject = JSONObject.fromObject(field);
            Set<Test> tests = testService.getTestByEquipmentId(Long.parseLong(jsonObject.get("equipmentId").toString()));
            if(tests == null){
                return ResultUtil.error(ResultEnum.ILLEGAL_EQUIPMENT_ID);
            }else{
                return ResultUtil.success(ResultEnum.INVOKE_SUCCESS,tests);
            }
        }else{
            return ResultUtil.error(ResultEnum.INVAILD_METHOD);
        }
    }
}
